﻿using Common.Commands;
using Common.Commands.MemberCommands;
using Common.Service;
using Common.Views;
using Core.Domain.Model;
using NSBus.Dto.Commands;
using NServiceBus;
using Sanelib.Common.Helpers;
using Sanelib.DataOperation;
using Sanelib.DataView;
using Sanelib.Dto;

namespace Core.Processors.MemberProcessors
{
    public class ChangePasswordProcessor : ICommandProcessor<ChangePassword>
    {
        private readonly IRepository<Member> _repository;
        private readonly IViewRepository<TempleteView> _templeteViewRepository;
        private readonly ICryptographer _cryptographer;
        public IBus Bus { get; set; }

        private const string MessageSubject = "Sanelib Password Changed Notification";

        private string _messageBody;

        public ChangePasswordProcessor(IRepository<Member> repository, ICryptographer cryptographer, IViewRepository<TempleteView> templeteViewRepository)
        {
            _repository = repository;
            _cryptographer = cryptographer;
            _templeteViewRepository = templeteViewRepository;
        }

        public dynamic Process(ChangePassword command)
        {
            var response = new WebApiResultResponse();
            var member = _repository.GetById(command.Id);

            var salt = _cryptographer.CreateSalt();
            var hash = _cryptographer.ComputeHash(command.NewPassword + salt);

            member.PasswordHash = hash;
            member.PasswordSalt = salt;
            member.LastPasswordChangedDate = SystemTime.Now();
            member.PasswordRetrievalToken = "";
            member.PasswordRetrievalTokenExpirationDate = SystemTime.Now();

            _repository.Update(member);


            if (string.IsNullOrEmpty(member.Email))
            {
                _messageBody = string.Format(_templeteViewRepository.GetByKey(Property.Of<TempleteView>(x => x.Name), "Change Passowrd Dynamic Templete").Value, member.Name, member.Mobile);

                if (_messageBody != null)
                    Bus.Send("NSBus.Server", new SendEmailCommand
                    {
                        MessageBody = _messageBody,
                        Subject = MessageSubject,
                    });

                response.IsSuccess = true;
                return response;
            }

            _messageBody = _templeteViewRepository.GetByKey(Property.Of<TempleteView>(x => x.Name), "Change Passowrd Fix Templete").Value;
            if (_messageBody != null)
                Bus.Send("NSBus.Server", new SendEmailCommand
                {
                    Subject = MessageSubject,
                    MessageBody = _messageBody,
                    To = member.Email
                });

            response.IsSuccess = true;
            return response;
        }
    }
}